package com.sx.exception;

import com.alibaba.fastjson.JSON;
import com.sx.basic.ResponseEntity;
import com.sx.basic.exception.BasicException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author AdinZ
 * @date 2020/7/15 18:33
 */
@ControllerAdvice@ResponseBody
public class GlobalExceptionHandler {
    private Logger log= LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.OK)@ResponseBody
    public ResponseEntity errorHandler(HttpServletRequest request, NoHandlerFoundException exception, HttpServletResponse response) {
        this.log(request,exception);
        return new ResponseEntity(HttpStatus.NOT_FOUND.value(),exception.getMessage());
    }

    @ExceptionHandler(value = BasicException.class)
    @ResponseStatus(HttpStatus.OK)@ResponseBody
    public ResponseEntity errorHandler(HttpServletRequest request, BasicException exception, HttpServletResponse response) {
        this.log(request,exception);
        return new ResponseEntity(exception.getCode(),exception.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity errorHandler(HttpServletRequest request, RuntimeException exception, HttpServletResponse response) {
        this.log(request,exception);
        return new ResponseEntity(500,exception.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity errorHandler(HttpServletRequest request, Exception exception, HttpServletResponse response) {
        this.log(request,exception);
        return new ResponseEntity(500,exception.getMessage());
    }


    private void log(HttpServletRequest request, Exception exception){
        try {
            log.error("接口发生异常, 请求url:{}, 参数:{},  post:{}  ,  error:", request.getRequestURI(),
                    JSON.toJSONString(request.getParameterMap()),
                    IOUtils.toString(request.getInputStream(),"utf8"),
                    exception.getMessage()
            );
            exception.printStackTrace();
        }catch (Exception e){
        }
    }

}
